﻿<%@ Page language="C#" MasterPageFile="~masterurl/default.master" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormSection" src="/_controltemplates/InputFormSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormControl" src="/_controltemplates/InputFormControl.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ButtonSection" src="/_controltemplates/ButtonSection.ascx" %>
<%@ Register Tagprefix="wssawc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>


<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false"></script>
<style>
.ContactName
{
     font-weight: bold;
}
</style>
<script type="text/javascript">
  ExecuteOrDelayUntilScriptLoaded(getAddress,"sp.js");
  var geocoder;
  var map;
  var currentItem = [];
  var j = 0;
  var currentLib;
  var address = [];
  var markerBounds = []; 
  var failedAddr = 0;
  function getAddress()
  {

   // var args = SP.UI.ModalDialog.get_childDialog().get_args();
   var args = window.frameElement.dialogArgs;
    var listId = args.listId;
    var selectedItems = args.selectedItems;
    
    var ctx = SP.ClientContext.get_current();
    web = ctx.get_web();

    currentLib = web.get_lists().getById(listId);

    for (var i = 0; i < selectedItems.length; i++) {
        currentItem[j] = currentLib.getItemById(selectedItems[i].id);
        ctx.load(currentItem[j]);
        j++;
    }
    ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccessDelegate), Function.createDelegate(this, this.onFailDelegate));
  }
   function onSuccessDelegate(sender, args) 
    {
        for (var i = 0; i < currentItem.length; i++)
        {
            var firstname = "",lastname = "",country="",addr,name,hasAttachment;

            addr = currentItem[i].get_item('WorkAddress') + ", " + currentItem[i].get_item('WorkZip') + " " + currentItem[i].get_item('WorkCity');
            
            if(currentItem[i].get_item('FirstName') != null)
                firstname = currentItem[i].get_item('FirstName');
            if(currentItem[i].get_item('Title') != null)
                lastname = currentItem[i].get_item('Title');
            if(currentItem[i].get_item('WorkCountry') != null)
                country = currentItem[i].get_item('WorkCountry');

            name =  firstname + " " + lastname ;

            hasAttachment = currentItem[i].get_fieldValues()['Attachments'];

            if(hasAttachment)
            {
                var url = String.format('{0}/Attachments/{1}/ContactPicture.jpg',currentItem[i].get_fieldValues()['FileDirRef'],currentItem[i].get_fieldValues()['ID']);
                address.push([addr,url,name,country]);
            }
            else
                address.push([addr,'',name,country]);
        }
        getMap();
    }
   function onFailDelegate(sender, args) 
    {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
  function getMap() {
    
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("mymap"), myOptions);

    setLocation();
    }
    function setLocation()
    {
        var total_Addr = address.length;
        var addrCount = 0;
        var flgOneAddr = false;
        

        if(total_Addr == 1)
            flgOneAddr = true;

         for (var i = 0; i < address.length; i++)
        {
            geocoder = new google.maps.Geocoder();
            if (geocoder) 
            {
                geocoder.geocode( { 'address': address[i][0]}, function(results, status) 
                {
                    if (status == google.maps.GeocoderStatus.OK) 
                    {
                            addrCount ++;
                            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) 
                            {
                                map.setCenter(results[0].geometry.location);
                                var ContentHtml;
                                var addrArr = address[addrCount - 1][0].split(",");
                                if(address[addrCount - 1][1] != '')
                                   ContentHtml = '<table><tr><td><img src="'+address[addrCount - 1][1]+'" width=100 height=100 /></td><td><div class=ContactName>'+address[addrCount - 1][2]+'</div>'+addrArr[0]+'<br />'+addrArr[1]+'<br />'+address[addrCount - 1][3]+'<td></tr></table>';
                                else
                                    ContentHtml = '<table><tr><td><div class=ContactName>'+address[addrCount - 1][2]+'</div>'+addrArr[0]+'<br />'+addrArr[1]+'<br />'+address[addrCount - 1][3]+'<td></tr></table>';

                                var infowindow = new google.maps.InfoWindow(
                                { 
                                    content: ContentHtml,
                                    size: new google.maps.Size(350,200)
                                });
                                var marker = new google.maps.Marker({
                                   position: results[0].geometry.location,
                                    map: map
                                  });

                                if(flgOneAddr == false)
                                {
                                    var myLatLng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());                      
                                    addressesBounds(total_Addr, addrCount, myLatLng);  
                               }
                               else
                               {
                                    map.setZoom(12);
                               }
                                 google.maps.event.addListener(marker, 'dblclick', function() 
                               {
                                    infowindow.open(map,marker);
                                     map.setZoom(12);

                                });
                                 google.maps.event.addListener(marker, 'click', function() 
                               {
                                    infowindow.open(map,marker);

                                });
                            } 
                            else 
                            {
                            alert("No results found");
                            }
                    } 
                    else 
                    {
                        addrCount ++;
                        failedAddr++;
                        alert("Map was not successful for the address : " + address[addrCount - 1][0]);

                         if (total_Addr == failedAddr) 
                            SP.UI.ModalDialog.commonModalDialogClose();
                    }
                 });
            }
        }
    }

    function addressesBounds(total_addresses, address_count, myLatLng) {

    markerBounds.push(myLatLng);

    // make sure you only run this function when all addresses have been geocoded
    if (total_addresses == address_count) {
        var latlngbounds = new google.maps.LatLngBounds();
        for ( var i = 0; i < markerBounds.length; i++ ) {
           latlngbounds.extend(markerBounds[i]);
        }
        map.setCenter(latlngbounds.getCenter());
        map.fitBounds(latlngbounds);

        if(address_count - failedAddr == 1)
            map.setZoom(12);
    }
}

</script>
<table class="ms-propertysheet" border="0" width="100%" cellspacing="0" cellpadding="0">
	<div id="mymap" style="width:1300px;height:600px">Map</div>
</table>

</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
	
</asp:Content>
<asp:Content ID="PageTitle" ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
	<SharePoint:EncodedLiteral ID="EncodedLiteral1" runat="server" text="Map" />
</asp:Content>

